const Metro = require('metro');

const path = require("path")
const fs = require("fs")

const { runBuild } = require('./pack-base')
const child_process = require('child_process');




function execSync(cmd, options = {}, log = true) {
  const stdout = child_process.execSync(cmd, {
    encoding: "utf-8",
    ...options
  })
  if (log) console.log(stdout)
  return stdout
}






const argv = process.argv;
const configFile = argv[2]
if (!configFile) {
  throw ("config is empty")
}
const configPath = path.join(__dirname, `/bundle/${configFile}`)
const config = require(configPath)
const { name, entry = "index.js", output = "entry.js", zip, common = false, platforms = ["android", "ios"], metroConfig = './metro-bussiness.config.js', assetsDest = true } = config;

function format(value) {
  const REGEXP = /\[\\*([\w:]+)\\*\]/gi;
  value = value.replace(REGEXP, (match, content) => {
    if (content.length + 2 === match.length) {
      const contentMatch = /^(\w+)(?::(\w+))?$/.exec(content);
      if (!contentMatch) return match;
      const [, kind] = contentMatch;
      const v1 = process.env[kind]
      if (v1) {
        return v1
      }
    } else if (match.startsWith("[\\") && match.endsWith("\\]")) {
      return `[${match.slice(2, -2)}]`;
    }
    return match;
  })
  return value
}

async function deleteDir(dir, holdCurrent = false) {
  if (fs.existsSync(dir)) {
    const files = fs.readdirSync(dir)
    for (const file of files) {
      const p1 = path.join(dir, file)
      const stat = fs.statSync(p1)
      if (stat.isFile()) {
        fs.unlinkSync(p1)
      } else {
        deleteDir(p1)
      }
    }
    if (!holdCurrent) {
      await fs.rmdirSync(dir)
    }
  }
}

async function run() {

  for (let platform of platforms) {
    console.log(name, platform, common)
    process.env.platform = platform
    await deleteDir(`./bundle-${platform}`, true)
    const bussinessConfig = await Metro.loadConfig({
      maxWorkers: 1,
      config: metroConfig,
    });
    await runBuild(bussinessConfig, {
      entry,
      out: `bundle-${platform}/${format(output)}`,
      platform,
      minify: true,
      dev: false,
      assetsDest: assetsDest ? `bundle-${platform}` : null,
    });
    // 壓縮
    const cwd = path.join(__dirname, `/bundle-${platform}`)
    var cmd = `zip -r -o ../bundle/${format(zip)} .`
    execSync(cmd, {
      cwd
    })



  }

}
// console.log(deleteDir('./bundle-ios'))
run();
// process.env.platform = "android"
// console.log(format('[platform].js'))

// process.env.platform = "ios"
// console.log(format('[platform].js'))